package com.say.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;

import com.say.bean.domain.Config;
import com.say.dao.ConfigDao;
import com.say.framework.core.common.service.BaseServiceImpl;
import com.say.framework.core.persistence.DynamicSpecifications;
import com.say.framework.core.persistence.SearchFilter;
import com.say.service.ConfigService;


/**
 * 
 * 类名称：ConfigServiceImpl<br>
 * 类描述：系统参数服务接口实现<br>
 * @version v1.0
 *
 */
@Service("configService")
public class ConfigServiceImpl extends BaseServiceImpl<Config, String> implements ConfigService {

    @Autowired
    public ConfigDao configDao;

    @Override
    public PagingAndSortingRepository<Config, String> getDao() {
        return configDao;
    }

    private static Map<String, String> configMap = new HashMap<String, String>();

    /**
     * 初始化系统参数数据
     */
    private void initConfigMap() {
        configMap = new HashMap<String, String>();
        List<Config> list = configDao.findAll();
        if (list != null && list.size() > 0) {
            Config config = null;
            for (int i = 0; i < list.size(); i++) {
                config = list.get(i);
                configMap.put(config.getCode(), config.getValue());
            }
        }
    }

    public String getCacheConfigByCode(String code) {
        String value = configMap.get(code);
        if (StringUtils.isEmpty(value)) {
            initConfigMap();
            value = configMap.get(code);
        }
        return value; 
    }

	@Override
	public Page<Config> findByPage(Map<String, Object> params, Pageable sp) {
		 Map<String, SearchFilter> filters = SearchFilter.parse(params);
	     Specification<Config> specification = DynamicSpecifications.bySearchFilter(filters.values(), Config.class);
	     return configDao.findAll(specification, sp);
	}

	@Override
	public Config getConfigByCode(String code) {
		return configDao.getConfigByCode(code);
	}

	@Override
	public Config saveConfig(Config config) {
		configDao.save(config);
		initConfigMap();
		return config;
	}

	
}
